package com.example.myapplicationktkt2.network

import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * OkHttp工具类
 * 封装了常用的网络请求方法
 */
class OkHttpUtil private constructor() {
    
    private val client: OkHttpClient = OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .build()
    
    /**
     * 发送GET请求
     * @param url 请求URL
     * @param callback 回调接口
     */
    fun get(url: String, callback: Callback) {
        val request = Request.Builder()
            .url(url)
            .build()
        
        client.newCall(request).enqueue(callback)
    }
    
    /**
     * 发送POST请求
     * @param url 请求URL
     * @param jsonBody JSON格式的请求体
     * @param callback 回调接口
     */
    fun post(url: String, jsonBody: String, callback: Callback) {
        val JSON = "application/json; charset=utf-8".toMediaType()
        val body = jsonBody.toRequestBody(JSON)
        
        val request = Request.Builder()
            .url(url)
            .post(body)
            .build()
        
        client.newCall(request).enqueue(callback)
    }
    
    companion object {
        @Volatile
        private var INSTANCE: OkHttpUtil? = null
        
        /**
         * 获取OkHttpUtil单例实例
         * @return OkHttpUtil实例
         */
        fun getInstance(): OkHttpUtil {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: OkHttpUtil().also { INSTANCE = it }
            }
        }
    }
}